<!--
 * @Author: zhoulei0232
 * @Date: 2023-04-01 23:03:20
 * @LastEditTime: 2023-04-14 01:21:01
 * @LastEditors: zhoulei0232
 * @Description: 
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="抢购点击QQ" prop="queryQiangQQ">
        <el-input
          v-model="queryParams.queryQiangQQ"
          placeholder="按QQ号码进行模糊查询"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="购买人QQ" prop="queryUserQQ">
        <el-input
          v-model="queryParams.queryUserQQ"
          placeholder="按QQ号码进行模糊查询"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="queryContent">
        <el-input
          v-model="queryParams.queryContent"
          placeholder="按商品名称进行模糊查询"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="queryStatus">
        <el-select
          v-model="queryParams.queryStatus"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="dict in approveStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="下单日期">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="multiple"
          @click="handleAllApprove"
          v-hasPermi="['business:goods:edit']"
          >批量审核</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:goods:remove']"
          >删 除</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="pageList"
      height="780px"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="100" />
      <el-table-column label="付款凭证" align="center" prop="src" width="320">
        <template #default="scope">
          <div class="invitation-image-list">
            <div v-for="(item, index) in scope.row.imagesList" :key="index">
              <el-image
                :key="index"
                style="width: 100px; height: 100px"
                :src="uploadShowUrl + item"
                :preview-teleported="true"
                :preview-src-list="[uploadShowUrl + item]"
                fit="contain"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品名称"
        align="center"
        prop="goodsName"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="抢购点击QQ"
        align="center"
        prop="pointerUserQQ"
        width="150"
      />
      <el-table-column
        label="使用人QQ"
        align="center"
        prop="userQQ"
        width="150"
      />
      <el-table-column
        label="使用人昵称"
        align="center"
        prop="nickname"
        width="150"
      />
      <el-table-column label="金额" align="center" prop="price" width="150" />
      <el-table-column
        label="审核状态"
        align="center"
        prop="status"
        width="150"
      >
        <template #default="scope">
          <dict-tag :options="approveStatusList" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column
        label="下单时间"
        align="center"
        prop="createdAt"
        width="250"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createdAt, "{y}-{m}-{d} {h}:{m}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="修改日期"
        align="center"
        prop="updatedAt"
        width="250"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.updatedAt, "{y}-{m}-{d} {h}:{m}:{s}") || "-"
          }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="280"
        :fixed="desk"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleApprove(scope.row)"
            v-hasPermi="['business:goods:edit']"
            >审核</el-button
          >
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:goods:edit']"
            >修改</el-button
          > -->
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:goods:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核意见" prop="approve">
              <el-radio-group v-model="form.approve">
                <el-radio
                  v-for="dict in approveList"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog :title="title" v-model="open1" width="780px" append-to-body>
      <el-form
        ref="noticeRef1"
        :model="form1"
        :rules="rules1"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input
                disabled
                placeholder="请输入商品名称"
                v-model="form1.goodsName"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="订单编号" prop="orderId">
              <el-input
                disabled
                placeholder="请输入订单编号"
                v-model="form1.orderId"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="接收人QQ" prop="takeoutQQ">
              <el-input placeholder="请输入接收人QQ" v-model="form1.takeoutQQ">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="转让日期" prop="createTime">
              <el-date-picker
                v-model="form1.createTime"
                type="date"
                placeholder="请输入转让日期"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入备注"
                v-model="form1.remarks"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel1">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导出 -->
    <el-dialog :title="title" v-model="openExprot" width="450px" append-to-body>
      <el-form
        ref="exprotRef"
        :model="formExprot"
        :rules="rulesExprot"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核日期" prop="dateRange">
              <el-date-picker
                v-model="formExprot.dateRange"
                type="month"
                format="YYYY-MM"
                value-format="YYYY-MM"
                placeholder="选择导出月份"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            :loading="loadingBtn"
            @click="debouncedFnExprot"
            >确 定</el-button
          >
          <el-button @click="cancelExprot">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BuyExamine">
import {
  updateOrderApply,
  downExcelOrderApply,
} from "@/api/business/orderApply";

import {
  listOrderSeckill,
  updateOrderSeckill,
  addOrderSeckill,
  deleteOrderSeckill,
  applyOrderSeckill,
} from "@/api/goods/buyExamine";

import useDesk from "@/hooks/useDesk";

import { useDebounceFn } from "@vueuse/core";

const { proxy } = getCurrentInstance();
// 图片上传地址
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadCos/goods";
const uploadShowUrl = import.meta.env.VITE_APP_COS_API;
const imageUrl = ref("");
const dateRange = ref([]);
const dateRange1 = ref([]);
const pageList = ref([]);
const open = ref(false);
const open1 = ref(false);
const openExprot = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const loadingBtn = ref(false);

const { desk } = useDesk();
// 状态 0 创建   1补充信息   2审核通过    3不通过
const approveStatusList = ref([
  {
    label: "不通过",
    value: "3",
    elTagClass: "",
    elTagType: "danger",
  },
  {
    label: "审核通过，订单已生成",
    value: "2",
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "待审核",
    value: "1",
    elTagClass: "",
    elTagType: "warning",
  },
  {
    label: "待完善信息",
    value: "0",
    elTagClass: "",
    elTagType: "danger",
  },
]);

const approveList = ref([
  { label: "通过", value: 2 },
  { label: "不通过", value: 3 },
]);

const data = reactive({
  form: {},
  form1: {},
  formExprot: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    queryUserName: undefined,
    queryContent: undefined,
    queryOrderIdIn: undefined,
    queryApprove: undefined,
  },
  rules: {
    approve: [
      { required: true, message: "审核状态不能为空", trigger: "change" },
    ],
  },
  rules1: {
    takeoutQQ: [{ required: true, message: "QQ不能为空", trigger: "blur" }],
    createTime: [{ required: true, message: " 不能为空", trigger: "change" }],
  },
  rulesExprot: {
    dateRange: [{ required: true, message: " 不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules, form1, rules1, formExprot, rulesExprot } =
  toRefs(data);

/** 查询公告列表 */
function getList() {
  loading.value = true;
  let sendData = proxy.addDateRangeZL(
    queryParams.value,
    dateRange.value,
    "CreateTime"
  );
  sendData = proxy.addDateRangeZL(sendData, dateRange1.value, "UpdateTime");

  listOrderSeckill(sendData).then((response) => {
    pageList.value = response.data.rows.map((item) => {
      let imagesList = [];
      if (item.src) {
        imagesList = item.src.split(",");
      }
      return {
        ...item,
        imagesList: imagesList,
      };
    });

    total.value = response.data.count;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 取消按钮 */
function cancel1() {
  open1.value = false;
  reset1();
}
/** 取消按钮 */
function cancelExprot() {
  openExprot.value = false;
  resetExprot();
}

/** 表单重置 */
function reset() {
  form.value = {
    approve: undefined,
    remark: undefined,
  };
  imageUrl.value = null;
  proxy.resetForm("noticeRef");
}
/** 表单重置1 */
function reset1() {
  form1.value = {};
  proxy.resetForm("noticeRef1");
}
function resetExprot() {
  formExprot.value = {};
  proxy.resetForm("exprotRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.queryUserName = undefined;
  queryParams.value.queryContent = undefined;
  queryParams.value.queryApprove = undefined;
  queryParams.value.queryQiangQQ = undefined;
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 批量审核按钮操作 */
function handleAllApprove() {
  let approveId = ids.value;
  if (approveId.length === 0) {
    return;
  }
  form.value.id = approveId;
  open.value = true;
  title.value = "批量审批";
}
/**审核按钮操作 */
function handleApprove(row) {
  let approveId = row.id || ids.value;
  if (!Array.isArray(approveId)) {
    approveId = [approveId];
  }
  form.value.id = approveId;
  open.value = true;
  title.value = "审批";
}
/**修改按钮操作 */
function handleUpdate(row) {
  reset1();
  if (!row.id) {
    let arr = pageList.value.filter((item) => {
      return item.id == ids.value;
    });
    form1.value = {
      ...arr[0],
    };
  } else {
    form1.value = {
      ...row,
    };
  }

  open1.value = true;
  title.value = "修改";
}
// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);
// 防抖操作
const debouncedFnExprot = useDebounceFn(
  () => {
    submitFormExprot();
  },
  1000,
  { maxWait: 3000 }
);
// 导出按钮操作
function submitFormExprot() {
  proxy.$refs["exprotRef"].validate((valid) => {
    if (valid) {
      const dataForm = formExprot.value;

      let fileName = "转让公示";
      if (dataForm.dateRange) {
        fileName = fileName + dataForm.dateRange + ".xlsx";
      } else {
        fileName = fileName + ".xlsx";
      }
      if (dataForm.dateRange) {
        let Time = dataForm.dateRange;
        let y = new Date(Time).getFullYear(); //获取年份
        let m = new Date(Time).getMonth() + 1; //获取月份
        let begin = Time + "-01";
        let end = Time + "-" + new Date(y, m, 0).getDate(); //获取当月最后一日
        dataForm.beginTime = begin;
        dataForm.endTime = end;
      } else {
        dataForm.beginTime = undefined;
        dataForm.endTime = undefined;
      }
      loadingBtn.value = true;
      downExcelOrderApply(dataForm).then((response) => {
        loadingBtn.value = false;

        downFile(response, fileName);
      });
    }
  });
}
/** 提交按钮 */
function submitForm() {
  if (title.value == "修改") {
  } else {
    proxy.$refs["noticeRef"].validate((valid) => {
      if (valid) {
        let sendData = {
          ids: form.value.id,
          approve: form.value.approve,
        };

        applyOrderSeckill(sendData).then((response) => {
          proxy.$modal.msgSuccess("操作成功！");
          open.value = false;
          getList();
        });
      }
    });
  }
}
/** 删除按钮操作 */
function handleDelete(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }

  proxy.$modal
    .confirm('是否确认删除购买人QQ为"' + row.userQQ + '"的数据项？')
    .then(function () {
      return deleteOrderSeckill({ ids: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

// 排序
function handleSortChange(column) {
  let data1;
  if (column.order == "ascending") {
    data1 = "ASC";
  } else if (column.order == "descending") {
    data1 = "DESC";
  }
  if (!data1) {
    data.queryParams.orderName = undefined;
  } else {
    data.queryParams.orderName = column.prop;
  }
  data.queryParams.orderType = data1;
  getList();
}
// 打开导出弹框
function handleOpenExprot() {
  openExprot.value = true;
  title.value = "导出报表";
  resetExprot();
}
// 可以将此方法封装
function downFile(content, filename) {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement("a");
  eleLink.download = filename;
  eleLink.style.display = "none";
  // 字符内容转变成blob地址
  var blob = new Blob([content]);
  eleLink.href = URL.createObjectURL(blob);
  document.body.appendChild(eleLink);
  // 触发点击
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
  proxy.$modal.msgSuccess("操作成功");
}

getList();
</script>
<style lang="scss" scoped>
.color-blue {
  color: rgb(0, 119, 255);
  cursor: pointer;
}

.avatar-uploader {
  width: 200px;
  height: 300px;

  .avatar {
    width: 100%;
    height: 100%;
  }
}

.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.invitation-image-list {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
</style>
